package externalflame.systemdesign.newsfeed.service.impl;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import externalflame.systemdesign.newsfeed.dao.FriendDao;
import externalflame.systemdesign.newsfeed.dao.TweetDao;
import externalflame.systemdesign.newsfeed.dto.Page;
import externalflame.systemdesign.newsfeed.entity.Tweet;
import externalflame.systemdesign.newsfeed.service.TweetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@ConditionalOnProperty(name = "app.tweetService", havingValue = "Push")
@Service
public class PushTweetService implements TweetService {

    @Autowired
    TweetDao tweetDao;

    @Autowired
    FriendDao friendDao;

    IdentifierGenerator identifierGenerator = new DefaultIdentifierGenerator();

    @Override
    public Page<Tweet> getMyTweets(Long userId, Long pageSize, Long maxId) {
        List<Tweet> data = tweetDao.findTweetsInInterestTweet(userId, pageSize, maxId);
        Page<Tweet> page = new Page<>();
        page.setData(data);
        if (!data.isEmpty()) {
            maxId = data.get(data.size()-1).getId() + 1;
        } else {
            maxId = null;
        }
        if (maxId != null) {
            page.setMaxId(maxId.toString());
        } else {
            page.setMaxId(null);
        }
        page.setPageSize(pageSize);
        return page;
    }

    @Transactional(isolation = Isolation.SERIALIZABLE)
    @Override
    public Tweet postTweet(Long userId, String content) {
        Long tId = identifierGenerator.nextId(Tweet.class).longValue();
        Date now = new Date();
        tweetDao.add(tId, userId, content, now);
        tweetDao.addToInterestTweet(tId, userId, content, now, userId);
        List<Long> followers = friendDao.getFollowers(userId);
        for (Long fId: followers
             ) {
            tweetDao.addToInterestTweet(tId, userId, content, now, fId);
        }
        return new Tweet(tId, userId, content, now);
    }

    @Override
    public List<Tweet> getTimeline(Long userId, Long maxId, Long pageSize) {
        return tweetDao.findTweets(userId, maxId, pageSize);
    }
}
